<template>
	<div @click="showDate = true" :style="customStyle">{{ showName }}<van-icon name="arrow-down" class="d-mg-l5" /></div>
	<van-popup v-model:show="showDate" round position="bottom" :teleport="body">
		<van-date-picker v-model="date" @cancel="showDate = false" @confirm="onConfirm" :columns-type="dateType.split(',')"
			:formatter="formatter" :max-date="maxDate">
			<template #title>
				<van-dropdown-menu>
					<van-dropdown-item v-model="dateType" :options="dateTypeOption" />
				</van-dropdown-menu>
			</template>
		</van-date-picker>
	</van-popup>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'

const maxDate = ref(null);

const props = defineProps(['modelValue', 'style'])
const emits = defineEmits(['update:modelValue', 'confirm'])
const body = document.body
const showDate = ref(false)
const date = ref([''])
const dateType = ref('year,month')
const dateTypeOption = ref([{
	text: '按月',
	value: 'year,month'
},
{
	text: '按年',
	value: 'year'
}
])
const cy = (new Date()).getFullYear() + ''
const cm = ('0' + ((new Date()).getMonth())).slice(-2)
const currentYm = [cy, cm]
const showName = ref([`${cy}年`, `${cm}月`].join(''))

// 将传入的 style 绑定到变量
const customStyle = props.style || {}

const onConfirm = value => {
	showName.value = value.selectedOptions.map(d => d.text).join('')
	showDate.value = false
	const modelValue = value.selectedValues.join('-')
	emits('update:modelValue', modelValue)
	emits('confirm', modelValue)
}

const resetDate = () => {
	date.value = dateType.value === 'year,month' ? currentYm : currentYm.slice(0, 1)
}

const formatter = (type, option) => {
	if (type === 'year') {
		option.text += '年';
	}
	if (type === 'month') {
		option.text += '月';
	}
	return option;
}

watch(dateType, val => {
	resetDate()
}, {
	immediate: true
})

onMounted(() => {
	const today = new Date();
	maxDate.value = today; // 设置 maxDate 为当前日期
});

</script>

<style lang="scss" scoped>
:deep(.van-dropdown-menu) {
	.van-dropdown-menu__bar {
		background-color: none;
		box-shadow: none;
	}
}
</style>